package com.cxb.springboot.controller;

import com.cxb.springboot.domin.AntiRequest;
import com.cxb.springboot.domin.ZkData;
import com.cxb.springboot.service.ZkService;
import org.apache.curator.framework.recipes.atomic.AtomicValue;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicLong;
import org.apache.curator.framework.recipes.queue.DistributedQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Classname ZkService
 * @Date 2023/4/2 23:03
 * @Created by Administrator
 * @Description TODO
 */
@RestController
@RequestMapping("/zk")
public class ZkController {

    @Autowired
    private ZkService zkService;

    @Autowired
    private DistributedQueue distributedQueue;

    @Autowired
    private DistributedAtomicLong distributedIdGenerator;

    public static final String HRHK_ZT = "/HRHK_ZT/ST/";

    @GetMapping
    public ZkData getZkData(String code) throws Exception {
        return zkService.readZkData(zkService.getPath(code));
    }

    @PostMapping
    public void createZkData(@RequestBody ZkData zkData) throws Exception {
        zkService.storageData(zkService.getPath(zkData.getCode()), zkData);
    }

    @PutMapping
    public void updateZkData(@RequestBody ZkData zkData) throws Exception {
        zkService.updateData(zkService.getPath(zkData.getCode()), zkData);
    }

    @DeleteMapping
    public void deleteZkData(String code) {
        zkService.deleteNode(zkService.getPath(code));
    }


    @PostMapping("/test")
    public void test(@RequestBody AntiRequest antiMoneyDetail) throws Exception {
        distributedQueue.put(antiMoneyDetail);
        System.out.println(antiMoneyDetail);
    }

    /**
     * 创建分布式队列
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/create-id")
    public long generateId() throws Exception {
        AtomicValue<Long> result = distributedIdGenerator.increment();
        if (result.succeeded()) {
            return result.postValue();
        } else {
            throw new RuntimeException("Failed to generate ID");
        }
    }

}
